﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using lottery.api.Data;
using lottery.api.Models;
using lottery.api.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Polly;
using Polly.Extensions.Http;
using Polly.Timeout;
using Serilog;

namespace lottery.api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }


        static IAsyncPolicy<HttpResponseMessage> RetryPolicy()
        {
            return HttpPolicyExtensions.HandleTransientHttpError() // include: HTTP 5XX, HTTP 408 (timeout)
                .Or<TimeoutRejectedException>() // Polly的Timeout配置不会正常返回 408 response
                .WaitAndRetryAsync(3, times => TimeSpan.FromMilliseconds(600 * times), (resp, timespan) =>
                {
                    Log.Logger.Warning(resp.Exception, $"Retrying: {resp.Result?.StatusCode}");
                });
        }

        static IAsyncPolicy<HttpResponseMessage> CircuitBreakerPolicy()
        {
            return HttpPolicyExtensions.HandleTransientHttpError()
                .OrResult(resp => resp.StatusCode == HttpStatusCode.NotFound)
                .Or<TimeoutRejectedException>()
                .CircuitBreakerAsync(5, TimeSpan.FromMinutes(5), (resp, timespan) => // 执行5分钟短路保护策略之前允许5次故障
                {
                    Log.Logger.Warning(resp.Exception, $"Breaking: {resp.Result?.StatusCode}");
                }, () => Log.Logger.Warning("Break Reset"));
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IWechatService, WechatService>();
            services.AddHttpClient<IWechatService, WechatService>(c =>
            {
                c.BaseAddress = new Uri(Program.Configuration.GetConnectionString("Wechat"));
            })
            .AddPolicyHandler(request => Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(10)))
            .AddPolicyHandler(RetryPolicy())
            .AddPolicyHandler(CircuitBreakerPolicy());

            services.AddDbContext<LotteryContext>(options =>
                options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))
            );
            services.Configure<WechatOptions>(Configuration.GetSection("Wechat"));

            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.HttpOnly = true;
                options.Cookie.Name = ".wechat.session";
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseSession();
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
